package com.talos.ums.service.scopeorganization;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.scopeorganization.vo.UmsScopeOrganizationPageReqVO;
import com.talos.ums.controller.admin.scopeorganization.vo.UmsScopeOrganizationSaveReqVO;
import com.talos.ums.dal.dataobject.scopeorganization.UmsScopeOrganizationDO;
import com.talos.ums.dal.mysql.scopeorganization.UmsScopeOrganizationMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 经营范围组织关联表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsScopeOrganizationServiceImpl implements UmsScopeOrganizationService {

    @Resource
    private UmsScopeOrganizationMapper scopeOrganizationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createScopeOrganization(UmsScopeOrganizationSaveReqVO createReqVO) {
        // 插入
        UmsScopeOrganizationDO scopeOrganization = BeanUtils.toBean(createReqVO, UmsScopeOrganizationDO.class);
        scopeOrganizationMapper.insert(scopeOrganization);
        // 返回
        return scopeOrganization.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateScopeOrganization(UmsScopeOrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateScopeOrganizationExists(updateReqVO.getId());
        // 更新
        UmsScopeOrganizationDO updateObj = BeanUtils.toBean(updateReqVO, UmsScopeOrganizationDO.class);
        scopeOrganizationMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteScopeOrganization(Long id) {
        // 校验存在
        validateScopeOrganizationExists(id);
        // 删除
        scopeOrganizationMapper.deleteById(id);
    }

    private void validateScopeOrganizationExists(Long id) {
        if (scopeOrganizationMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsScopeOrganizationDO getScopeOrganization(Long id) {
        return scopeOrganizationMapper.selectById(id);
    }

    @Override
    public PageResult<UmsScopeOrganizationDO> getScopeOrganizationPage(UmsScopeOrganizationPageReqVO pageReqVO) {
        return scopeOrganizationMapper.selectPage(pageReqVO);
    }

}
